package com.xing.serviceedu.controller.front;

import com.alibaba.excel.util.StringUtils;
import com.xing.commonutils.JwtUtils;
import com.xing.commonutils.R;
import com.xing.commonutils.user.CourseWebVoOrder;
import com.xing.serviceedu.client.OrderClient;
import com.xing.serviceedu.entity.chapter.ChapterVo;
import com.xing.serviceedu.entity.vo.CourseWebVo;
import com.xing.serviceedu.service.EduChapterService;
import com.xing.serviceedu.service.EduCourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("eduservice/coursefront")
@CrossOrigin
public class CourseFrontController {

    @Autowired
    private EduCourseService eduCourseService;

    @Autowired
    private EduChapterService eduChapterService;

    @Autowired
    private OrderClient orderClient;


    //远程调用课程id获取课程信息
    @PostMapping("getCourseInfoOrder/{id}")
    public CourseWebVoOrder getCourseInfoOrder(@PathVariable String id) {

        CourseWebVo courseInfo = eduCourseService.getBaseCourseInfo(id);
        CourseWebVoOrder courseWebVoOrder = new CourseWebVoOrder();
        //把从数据库中查过来的值，浅拷贝给创建的对象，返回给前端
        BeanUtils.copyProperties(courseInfo, courseWebVoOrder);
        return courseWebVoOrder;
    }

    //课程详情的方法
    @GetMapping("getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable("courseId") String courseId, HttpServletRequest request) {
        boolean isBuyCourse = false;

        //根据课程id,编写sql语句查询课程信息
        //换个地方写，重新写这个方法
        List<ChapterVo> chapterVoList = eduChapterService.getChapterVoByCourseId(courseId);
        CourseWebVo courseWebVo = eduChapterService.getBaseCourseInfo(courseId);
        //根据课程id,查询章节和小节信息


        //造一条假数据
        String jwtToken = JwtUtils.getJwtToken("1", "1");
        System.out.println("jwtToken ====>:" + jwtToken);
        //获取用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);

        if (!StringUtils.isEmpty(memberId)) {
            //根据课程id,用户id，查询课程是否已经购买
            isBuyCourse = orderClient.isBuyCourse(memberId, courseId);
        }
        return R.ok().data("courseWebVo", courseWebVo).data("chapterVoList", chapterVoList).data("isBuyCourse", isBuyCourse);
    }


}
